<template>
  <div class="dish-container">
    <!-- 搜索和操作栏 -->
    <el-card class="search-card">
      <el-form :inline="true" :model="searchForm">
        <el-form-item label="菜品名称">
          <el-input v-model="searchForm.name" placeholder="请输入菜品名称" clearable />
        </el-form-item>
        <el-form-item label="所属餐厅">
          <el-select style="width: 150px" v-model="searchForm.restaurantId" placeholder="请选择餐厅" clearable>
            <el-option
              v-for="item in restaurants"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="状态">
          <el-select style="width: 150px" v-model="searchForm.status" placeholder="请选择状态" clearable>
            <el-option label="上架" :value="1" />
            <el-option label="下架" :value="0" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="resetSearch">重置</el-button>
          <el-button type="success" @click="handleAdd">新增菜品</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 数据表格 -->
    <el-card class="table-card">
      <el-table v-loading="loading" :data="tableData" border>
        <el-table-column type="index" label="序号" width="60" align="center"/>
        <el-table-column prop="name" label="菜品名称" width="200"/>
        <el-table-column prop="image" label="图片" width="200">
          <template #default="{ row }">
            <el-image
              v-if="row.image"
              :src="row.image"
              :preview-src-list="[row.image]"
              fit="cover"
              class="table-image"
            />
            <span v-else>暂无图片</span>
          </template>
        </el-table-column>
        <el-table-column prop="price" label="价格" width="150">
          <template #default="{ row }">
            ¥{{ row.price }}
          </template>
        </el-table-column>
        <el-table-column prop="restaurantName" label="所属餐厅" width="260"/>
        <el-table-column prop="categoryName" label="所属分类" />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="row.status === 1 ? 'success' : 'info'">
              {{ row.status === 1 ? '在售' : '已下架' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="280" fixed="right">
          <template #default="scope">
            <el-button type="primary" size="small" @click="handleEdit(scope.row)">编辑</el-button>
            <el-button
              :type="scope.row.status === 1 ? 'warning' : 'success'"
              size="small"
              @click="handleStatusChange(scope.row)"
            >
              {{ scope.row.status === 1 ? '下架' : '上架' }}
            </el-button>
            <el-button type="danger" size="small" @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 新增/编辑对话框 -->
    <el-dialog
      :title="dialogTitle"
      v-model="dialogVisible"
      width="600px"
      @close="handleDialogClose"
    >
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="菜品名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入菜品名称" />
        </el-form-item>
        <el-form-item label="所属餐厅" prop="restaurantId">
          <el-select
            v-model="form.restaurantId"
            placeholder="请选择餐厅"
            @change="handleRestaurantChange"
          >
            <el-option
              v-for="item in restaurants"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="分类" prop="categoryId">
          <el-select v-model="form.categoryId" placeholder="请选择分类">
            <el-option
              v-for="item in categories"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="价格" prop="price">
          <el-input-number
            v-model="form.price"
            :min="0"
            :precision="2"
            :step="1"
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item label="图片" prop="image">
          <el-upload
            class="dish-uploader"
            :action="`/api/file/upload`"
            :headers="uploadHeaders"
            :show-file-list="false"
            :on-success="handleUploadSuccess"
            :before-upload="beforeUpload"
          >
            <img v-if="form.image" :src="form.image" class="uploaded-image" />
            <el-icon v-else class="uploader-icon"><Plus /></el-icon>
          </el-upload>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio :label="1">上架</el-radio>
            <el-radio :label="0">下架</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input
            v-model="form.description"
            type="textarea"
            :rows="3"
            placeholder="请输入描述信息"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import axios from 'axios'
import { getCategoryDetail } from '@/api/category.js'



// 搜索表单数据
const searchForm = reactive({
  name: '',
  restaurantId: '',
  categoryId: '',
  status: ''
})

// 表格数据
const tableData = ref([])
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const loading = ref(false)

// 餐厅和分类数据
const restaurants = ref([])
const categories = ref([])

// 对话框相关
const dialogVisible = ref(false)
const dialogTitle = ref('')
const formRef = ref()
const form = reactive({
  id: '',
  name: '',
  restaurantId: '',
  categoryId: '',
  price: 0,
  image: '',
  description: '',
  status: 1
})

// 上传相关
const uploadHeaders = {
  Authorization: `Bearer ${localStorage.getItem('token')}`
}

// 表单验证规则
const rules = {
  name: [
    { required: true, message: '请输入菜品名称', trigger: 'blur' },
    { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  restaurantId: [
    { required: true, message: '请选择所属餐厅', trigger: 'change' }
  ],
  categoryId: [
    { required: true, message: '请选择分类', trigger: 'change' }
  ],
  price: [
    { required: true, message: '请输入价格', trigger: 'blur' }
  ],
  image: [
    { required: true, message: '请上传图片', trigger: 'change' }
  ]
}

// 获取餐厅列表
const getRestaurants = async () => {
  try {
    const { data } = await axios.get('/api/restaurant/list/all')
    restaurants.value = data.data
  } catch (error) {
    console.error('获取餐厅列表失败:', error)
  }
}

// 获取分类列表
const getCategories = async (restaurantId) => {
  try {
    const { data } = await axios.get(`/api/category/getList?restaurantId=${restaurantId}`)
    categories.value = data.data
  } catch (error) {
    console.error('获取分类列表失败:', error)
  }
}

// 获取菜品列表
const getList = async () => {
  try {
    const params = {
      page: currentPage.value,
      size: pageSize.value,
      ...searchForm
    }
    const { data } = await axios.get('/api/dish/page', { params })
    tableData.value = data.data.records

    total.value = data.total
  } catch (error) {
    console.error('获取菜品列表失败:', error)
  }
}

// 搜索
const handleSearch = () => {
  currentPage.value = 1
  getList()
}

// 重置搜索
const resetSearch = () => {
  searchForm.name = ''
  searchForm.restaurantId = ''
  searchForm.categoryId = ''
  searchForm.status = ''
  categories.value = []
  handleSearch()
}

// 新增菜品
const handleAdd = () => {
  dialogTitle.value = '新增菜品'
  dialogVisible.value = true
  Object.assign(form, {
    id: '',
    name: '',
    restaurantId: '',
    categoryId: '',
    price: 0,
    image: '',
    description: '',
    status: 1
  })
  categories.value = []
}

// 编辑菜品
const handleEdit = async (row) => {
  dialogTitle.value = '编辑菜品'
  dialogVisible.value = true
  if (row.restaurantId) {
    await getCategories(row.restaurantId)
  }
  Object.assign(form, row)
}

// 餐厅选择改变时
const handleRestaurantChange = async (restaurantId) => {
  form.categoryId = ''
  if (restaurantId) {
    await getCategories(restaurantId)
  } else {
    categories.value = []
  }
}

// 图片上传前的校验
const beforeUpload = (file) => {
  const isImage = file.type.startsWith('image/')
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isImage) {
    ElMessage.error('只能上传图片文件!')
    return false
  }
  if (!isLt2M) {
    ElMessage.error('图片大小不能超过 2MB!')
    return false
  }
  return true
}

// 图片上传成功的回调
const handleUploadSuccess = (response) => {
  form.image = response.data
  ElMessage.success('上传成功')
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return

  await formRef.value.validate(async (valid) => {
    if (valid) {
      try {
        if (form.id) {
          await axios.put('/api/dish', form)
        } else {
          await axios.post('/api/dish', form)
        }
        ElMessage.success('保存成功')
        dialogVisible.value = false
        getList()
      } catch (error) {
        ElMessage.error('保存失败')
      }
    }
  })
}

// 更改状态
const handleStatusChange = async (row) => {
  try {
    await axios.put(`/api/dish/status/${row.id}/${row.status === 1 ? 0 : 1}`)
    ElMessage.success('状态更新成功')
    getList()
  } catch (error) {
    ElMessage.error('状态更新失败')
  }
}

// 删除菜品
const handleDelete = (row) => {
  ElMessageBox.confirm('确认删除该菜品吗？', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      await axios.delete(`/api/dish/${row.id}`)
      ElMessage.success('删除成功')
      getList()
    } catch (error) {
      ElMessage.error('删除失败')
    }
  })
}

// 分页
const handleSizeChange = (val) => {
  pageSize.value = val
  getList()
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  getList()
}

onMounted(() => {
  getRestaurants()
  getList()
})
</script>

<style scoped>
.dish-container {
  padding: 20px;
}

.search-card {
  margin-bottom: 20px;
}

.table-card {
  margin-bottom: 20px;
}

.dish-image {
  width: 50px;
  height: 50px;
  border-radius: 4px;
}

.dish-uploader {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  width: 178px;
  height: 178px;
}

.dish-uploader:hover {
  border-color: #409EFF;
}

.uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
  display: flex;
  justify-content: center;
  align-items: center;
}

.uploaded-image {
  width: 178px;
  height: 178px;
  display: block;
  object-fit: cover;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
</style>
